import $axios from './api'
import axios from 'axios';
import config from './config';
import { user, publishType } from '../model/index'
let expiredRequestArr: any[] = [];
const login = (data: user) => {
    return $axios({
        url: '/login',
        data: data,
        method: 'POST'
    })
}
const register = (data: user) => {
    return $axios({
        url: '/register',
        data: data,
        method: 'POST'
    })
}
const getToken = () => {
    return $axios({
        url: '/getToken',
        method: 'get'
    })
}
const publish = (data: publishType) => {
    return $axios({
        data: data,
        url: '/publish',
        method: 'POST'
    })
}
const getCardList = () => {
    return $axios({
        url: '/getCardList',
        method: 'get'
    })
}
const getChatInfo = (id: string) => {
    return $axios({
        url: '/getChatInfo',
        data: { chatId: id },
        method: 'POST'
    })
}
const setAttent = (data: { follower_Id: any; userId: string; isattent: boolean }) => {
    return $axios({
        url: '/addAttention',
        data: data,
        method: 'POST'
    })
}

// 存储当前因为 token 失效导致发送失败的请求
const saveErrorRequest = (expiredRequest: () => any) => {
    expiredRequestArr.push(expiredRequest);
}

/**
 * 执行当前存储的由于过期导致失败的请求
 */
const againRequest = () => {
    expiredRequestArr.forEach(request => {
        request();
        console.log(789);
        
    })
    clearExpiredRequest();
}

const clearExpiredRequest = () => {
    expiredRequestArr = [];
}
const updateTokenByRefreshToken = () => {
    axios({  
        method: 'post',  
        url: `${config.baseUrl}/refresh`,  
        headers: {  
            'refreshToken': localStorage.getItem('refreshToken')
        }  
      }).then((res: any) => {
        console.log(res);
        
        let {
            refreshToken, accessToken
        } = res.data.data;
        console.log('qwer');
        // 更新本地的token
        localStorage.setItem('accessToken', accessToken);
        localStorage.setItem('refreshToken', refreshToken);
        /**
         * 当获取了最新的 refreshToken, accessToken 后
         * 重新发起之前失败的请求
         */
        againRequest();
    })
}
let timer: any = null
const refreshToken = (expiredRequest: () => any) => {
    saveErrorRequest(expiredRequest);
    // 保证再发起更新时，已经没有了过期请求要进行存储
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
        updateTokenByRefreshToken();
    }, 500);
}


export {
    login,
    register,
    getToken,
    publish,
    getCardList,
    getChatInfo,
    setAttent,
    refreshToken,
    clearExpiredRequest
}